package com.hee.erp.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.hee.erp.filter.LoginContextHolder;
import com.hee.erp.pojo.LoginInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class JwtUtil {

    @Value("${jwt.timeout}")
    public void setExpiration(long timeout) {
        EXPIRATION = 1000 * 60 * timeout;
    }


    private static final String SECRET = "hee_erp_jwt_secret";

    //jwt过期时间，默认1小时
    public static long EXPIRATION = 1000 * 60 * 60;

    public static String createToken(String userId,String userDbKey){
        Long expireTimeMillis = System.currentTimeMillis() + EXPIRATION;
        Date expireDate = new Date(System.currentTimeMillis() + EXPIRATION);
        Map<String,Object> map = new HashMap<>();
        map.put("alg","HS256");
        map.put("typ","JWT");

        String token = JWT.create()
                .withHeader(map)
                .withClaim("userId",userId)
                .withClaim("userDbKey",userDbKey)
                .withClaim("expireTimeMillis",expireTimeMillis)
                .withExpiresAt(expireDate)
                .withIssuedAt(new Date())
                .sign(Algorithm.HMAC256(SECRET));

        return token;
    }

    public static Map<String, Claim> verifyToken(String token){
        DecodedJWT jwt = null;
        try{
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt = verifier.verify(token);
        }catch (Exception e){
            log.error(e.getMessage());
            return null;
        }
        return jwt.getClaims();
    }
}
